import java.util.Objects;
import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable;
    //啥时候去执行,此处的时间不是delay,而是绝对时间
    private long time;

    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        //手动换算一下时间
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    public int compareTo(MyTimerTask o) {
        //按照时间来进行比较  构成最小堆
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> taskQueue = new PriorityQueue<>();
    //也可以用this直接作为锁对象
    private Object locker = new Object();

    public MyTimer() {
        //这个线程负责不停的扫描上诉队列的队首元素 ,来确定是否要执行任务
        Thread t = new Thread(() ->{
            //先抛一下异常
            try{
                while (true) {
                    synchronized (locker) {
                        if (taskQueue.size() == 0) {
                            //为空就要等待
                            locker.wait();
                        }
                        MyTimerTask task = taskQueue.peek();  //取出队首元素看看
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            //时间到了 要执行
                            task.run();
                            taskQueue.poll();  //执行完就弹出去
                        } else {
                            //时间还没到  则要等待剩余的时间   不是死等
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //启动线程
        t.start();
    }

    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            taskQueue.offer(task);
            locker.notify();
        }
    }
}


public class Demo37 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
    }
}
